package yunjiao.javatutorials.guava.base;

import com.google.common.base.Equivalence;

/**
 * 字符串长度相等
 *
 * @author yangyunjiao
 */
public class StringLengthEquivalence extends Equivalence<String> {
    @Override
    protected boolean doEquivalent(String a, String b) {
        if (a == null && b == null) return true;
        if (a == null || b == null) return false;
        return a.length() == b.length();
    }

    @Override
    protected int doHash(String s) {
        return s == null ? 0 : s.length();
    }

    public static void main(String[] args) {
        Equivalence<String> equivalence = new StringLengthEquivalence();

        String str1 = "hello";
        String str2 = "world";
        String str3 = "hi";

        System.out.println(">>>equivalent() 方法");
        System.out.println(equivalence.equivalent(str1, str2)); // true，长度都是5
        System.out.println(equivalence.equivalent(str1, str3)); // false，长度不同

        System.out.println(">>>hash() 方法");
        System.out.println(equivalence.hash(str1)); // 5
        System.out.println(equivalence.hash(str2)); // 5，与str1相同

        System.out.println(">>>wrap() 和 unwrap() 方法");
        Equivalence<String> equivalence1 = new StringLengthEquivalence();

        Equivalence.Wrapper<String> wrapper1 = equivalence1.wrap(str1);
        Equivalence.Wrapper<String> wrapper2 = equivalence1.wrap(str2);

        // Wrapper 使用 Equivalence 的等价关系
        System.out.println(wrapper1.equals(wrapper2)); // true
        System.out.println(wrapper1.get()); // "hello"
    }
}
